package com.tgy.algorithm.base._数组和;

import java.util.HashMap;

/**
 *
 * [1,-2,1,0,2,1]
 *
 */
public class _整数最大子数组和 {


    public static int integerArr(int[] nums,int k) {
        if (nums == null || nums.length == 0) {
            return -1;
        }

        int retLen = -1;
        int len = nums.length;
        int[] preSums = new int[len];
        preSums[0] = nums[0];

        for (int i = 1; i < len; i++) {
            preSums[i] = preSums[i - 1] + nums[i];
        }

        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < len; i++) {
            Integer value = preSums[i] - k;
            if (!map.containsKey(preSums[i])) {
                map.put(preSums[i], i);
            }

            if (map.containsKey(value)){
                Integer index = map.get(value);
                retLen = Math.max(retLen,i - index);
            }
        }

        return retLen;
    }

    public static void main(String[] args) {
        // 1,-1,0,0,2
        int[] nums = {1,-2,1,0,2,1};
        int maxLen = integerArr(nums, 1);
        System.out.println(maxLen);
    }
}
